package com.hxs.learn.schedule.factory;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

/**
 * spring application context quartz job factory
 * 通过设置setApplicationContext来初始化AutowireCapableBeanFactory
 *
 * @author huxinsheng
 * @date 2018-04-18 17:55:22
 */
@Component
public class AutowiredSpringBeanJobFactory extends AdaptableJobFactory implements ApplicationContextAware {

    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        capableBeanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        // 进行注入,不加入这个,job中注释spring bean将会是null
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}